{% extends "base.html" %}
{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

{% block title %}Equipment: {{ object.entity_id }}{% endblock %}

{% block content %}
<div class="container">

  {% include "core/_breadcrumbs.html" %}

  {% load render_table from django_tables2 %}

  <div class="card mb-3">
    <div class="card-body">
      {% if tags_form %}
        {% include "core/_tags.html" with form_title='Add Tag' nodecor=True section_tag='h2' section_title=object.description form=tags_form items=tags head_tags=head_tags %}
        {% if head_tags %}
          {% include "core/_head_tags.html" with form=tags_form items=head_tags %}
        {% endif %}
      {% else %}
        <h2>Equipment {{ object.description }}</h2>
      {% endif %}
    </div>
  </div>

  {% if solaredge %}
    {% load decamel from core_tags %}
    <div class="card mb-3">
      <div class="card-body" id="solaredge">
        <h5 class="pr">SolarEdge Site Details <div class="a-rt">
          <b-spinner v-if="loading" label="Loading..." variant="secondary"></b-spinner>
          <a href="{% url 'core:equipment_solaredge_edit_view' object.entity_id %}" class="btn btn-primary ml-auto" role="button" v-if="!loading"><i class="fas fa-edit"></i> Edit</a>
          <button v-if="!loading" v-on:click="fetchSolaredgeData" class="btn btn-primary"><i class="fas fa-cloud-download-alt"></i> Get Details</button>
        </div></h5>
        <div class="row m-0">
          <div class="col-md order-md-first order-last">
            <div v-cloak v-if="error" class="text-danger">${ error }</div>
            {% if solaredge_task_id %}
            <div>
              <task-progress no-step-description :csrfmiddlewaretoken="csrfmiddlewaretoken" text="Getting detailed information from SolarEdge.  Please wait." task-id="{{ solaredge_task_id }}" v-on:complete="reloadPage"></task-progress>
            </div>
            {% else %}
              <div v-if="taskId" class="mb-3">
                <task-progress no-spinner no-step-description :csrfmiddlewaretoken="csrfmiddlewaretoken" text="Getting detailed information from SolarEdge.  Please wait." :task-id="taskId" v-on:complete="reloadPage"></task-progress>
              </div>
              {% if solaredge.site_details %}
                <div class="row mb-3" v-if="loading">Getting detailed information from SolarEdge.  Please wait.</div>
                {% if solaredge.site_details.fetchFailed %}
                  <div class="row se_fetchFailed mb-3">Please click on Get Details to get detailed information from SolarEdge.</div>
                {% endif %}
                {% for item, value in solaredge.site_details.items %}
                  {% if value %}
                    {% if item == 'location' %}
                      <div class="row se_{{item}}"><b class="mr-2">Address:</b><span>{{ solaredge.display_location }}</span></div>
                    {% elif item == 'primaryModule' %}
                      <div class="row se_{{item}}"><b class="mr-2">{{ item | decamel | title }}:</b><span>{{ solaredge.display_primary_module }}</span></div>
                    {% elif item == 'publicSettings' %}
                      <div class="row se_{{item}}"><b class="mr-2">{{ item | decamel | title }}:</b><span>{{ solaredge.display_public_settings }}</span></div>
                    {% elif item == 'uris' %}
                      {# skip this one #}
                    {% elif item == 'fetchFailed' %}
                      {# skip this one #}
                    {% else %}
                      <div class="row se_{{item}}"><b class="mr-2">{{ item | decamel | title }}:</b><span>{{ value }}</span></div>
                    {% endif %}
                  {% endif %}
                {% endfor %}
                {% if solaredge.meter %}
                  <div class="row"><b class="mr-2">Meter:</b> <a href="{{ solaredge.meter.get_absolute_url }}">{{ solaredge.meter }}</a> </div>
                {% endif %}
              {% else %}
                <p>SolarEdge data is being fetched ...</p>
              {% endif %}
            {% endif %}
          </div>
          {% if solaredge.site_image %}
          <div class="col ml-md-auto mb-2" style="max-width:250px">
            <div class="row mt-md-3">
              <a href="{{ solaredge.site_image.url }}" target="_blank">
              {% if solaredge.site_thumbnail %}
                <img src="{{ solaredge.site_thumbnail.url }}" alt="View Image"/>
              {% else %}
                View Image
              {% endif %}
              </a>
            </div>
          </div>
          {% endif %}
        </div>
      </div>
    </div>
  {% endif %}

  <div class="card mb-3">
    <div class="card-body">
      <div id="dashboard_button">
          <div class="alert alert-danger mt-3" role="alert" v-if="errors.error" v-cloak>
            ${ errors.error }
          </div>
          <div class="alert alert-success mt-3" role="alert" v-if="successes.success" v-cloak>
            ${ successes.success }
          </div>
          <h3>
            <div class="row m-0">
              <div>Data Points</div>
              <div class="text-right flex-grow-1" v-if="is_ahu" v-cloak>
                <a v-if="dashboard_uid" :href="get_dashboard_url()" target="_blank" v-cloak><img width="32" src="{% static 'images/grafana_icon.svg' %}" /></a>
                <a v-if="!dashboard_uid" href="#" v-on:click="create_dashboard" v-cloak ><img width="32" src="{% static 'images/grafana_icon.svg' %}" /></a>
              </div>
            </div>
          </h3>
          <iframe :src="get_dashboard_snapshot_url()" width="100%" height="300" frameborder="0" v-if="is_ahu && dashboard_uid && get_dashboard_snapshot_url()" v-cloak></iframe>
      </div>
      <hr class="mt-0"/>
      <div id="datetimelist">
        <h5 class="form-title position-relative" v-b-toggle.collapse_datapoints>
          {{ data_points }} Data Points
          <b-button variant="light" size="sm" class="a-rt when-opened">
             <i class="fa fa-chevron-up"></i>
          </b-button>
          <b-button variant="light" size="sm" class="a-rt when-closed">
             <i class="fa fa-chevron-down"></i>
          </b-button>
        </h5>

        <b-collapse v-cloak id="collapse_datapoints" v-on:show="show_collapse('collapse_datapoints', '{{object.entity_id}}')">
          <p>Loading ...</p>
        </b-collapse>
      </div>
    </div>
  </div>

  {% if file_upload_form %}
    {% include "core/_upload.html" with form_title='Upload File' link_form_title='Add Link' form=file_upload_form items=files %}
  {% endif %}

  {% if notes_form %}
    {% include "core/_notes.html" with form_title='Add Note' form=notes_form items=notes %}
  {% endif %}

</div>
<script>
(function(){
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';

  new Vue({
    delimiters: ['${', '}'],
    el: '#datetimelist',
    methods: {
      show_collapse(container_id, equipment_id) {
        container = document.getElementById(container_id)
        container.innerHTML = '<p>Loading ...</p>'
        url = dutils.urls.resolve('equipment_data_points_table', { id: equipment_id })
        axios.get(url).then(response => {
          container.innerHTML = response.data
        });
      }
    }
  });
  new Vue({
    delimiters: ['${', '}'],
    el: '#solaredge',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        loading: false,
        error: false,
        taskId: false
      }
    },
    methods: {
      fetchSolaredgeData: function(e) {
        console.log('fetchSolaredgeData: should start a new task...')
        // cleanup previous error if any
        els = this.$el.getElementsByClassName('se_fetchFailed')
        if (els && els.length) {
          els[0].remove()
        }
        const formData = new FormData()
        formData.set('csrfmiddlewaretoken', this.csrfmiddlewaretoken)
        this.error = false
        this.loading = true
        this.taskId = false
        axios.post('{% url 'core:equipment_fetch_solaredge_details' object.entity_id %}', formData)
          .then(x => x.data)
          .then(x => {
            this.loading = false
            console.log('fetchSolaredgeData got', x)
            if (x.error) {
              this.error = x.error
            } else if (x.success == 'async') {
              // display the task progress instead
              this.loading = true
              this.taskId = x.task_id
            } else {
              this.reloadPage()
            }
          })
          .catch(err => {
            this.loading = false
            console.error('fetchSolaredgeData error :', err)
            this.error = err
          });
      },
      reloadPage: function() {
        console.log('task finished, reloading page')
        location.reload()
      }
    }
  });
  new Vue({
    delimiters: ['${', '}'],
    el: '#dashboard_button',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        equipment_id:  '{{ object.entity_id|safe }}',
        dashboard_uid: '{{ object.dashboard_uid|safe }}',
        dashboard_snapshot_uid: '{{ object.dashboard_snapshot_uid|safe }}',
        grafana_url: '{{ grafana_url }}',
        grafana_snapshot_url: '{{ grafana_snapshot_url }}',
        errors: false,
        successes: false,
        is_ahu: {{ is_ahu|safe }},
      }
    },
    methods: {
      get_dashboard_url: function () {
          var url = null;
          if (this.grafana_url && this.dashboard_uid) {
            url = this.grafana_url + this.dashboard_uid
          }

          return url;
      },
      get_dashboard_snapshot_url: function () {
          var url = null;
          if (this.grafana_snapshot_url && this.dashboard_snapshot_uid && this.dashboard_snapshot_uid != 'None') {
            url = this.grafana_snapshot_url + this.dashboard_snapshot_uid + '?orgId=1&kiosk&fullscreen&panelId=2'
          }

          return url;
      },
      create_dashboard : function(){
        const formData = new FormData();
        formData.set('csrfmiddlewaretoken', this.csrfmiddlewaretoken)
        url = dutils.urls.resolve('equipment_dashboard', {id: this.equipment_id})
        this.errors = false
        this.successes = false
        return axios.post(url, formData)
            .then(x => x.data)
            .then(x => {
              console.log('create_dashboard Done', x)
              if (x.success) {
                this.dashboard_uid = x.dashboard_uid
                if (x.dashboard_snapshot_uid) {
                    this.dashboard_snapshot_uid = x.dashboard_snapshot_uid
                } else {
                    this.dashboard_snapshot_uid = null
                }
                this.successes = {'success': x.success}
                return x
              } else {
                return Promise.reject(x.errors)
              }
            })
            .catch(err => {
              console.error('create_dashboard error :', err)
              this.errors = getResponseError(err)
            });
      },
    }
  });
})();
</script>
{% endblock content %}
